import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:get/get.dart';
import 'package:hygf/config/ApiConfig.dart';
import 'package:hygf/config/GlobalConfig.dart';
import 'package:hygf/http/file_transfer/down_cap.dart';
import 'package:hygf/util/location/location_gaode.dart';
import 'package:intl/intl.dart';

import '../../../bean/customer_bean.dart';
import '../../../http/DioClient.dart';
import '../../../http/core/ResponseData.dart';
import '../../../util/HDNavigator.dart';
import '../../../util/LoadingUtils.dart';
import '../../../util/cache_util.dart';
import '../../../util/location/location_manager.dart';
import '../../../view/image_picker_widget.dart';
import 'state.dart';

class BusinessLogic extends GetxController {
  final BusinessState state = BusinessState();
  bool isRefresh = false;

  @override
  void onInit() {
    super.onInit();
    initAccessToken();
    LocationGaode().startLocation((location) => {});
  }

  @override
  void onReady() {
    super.onReady();
    if((CacheUtil().getJson("customerBean")??{}).isNotEmpty){
      state.customerBean = CustomerBean.fromJson((CacheUtil().getJson("customerBean")??{}));
      initImgUrl();
    }
  }

  @override
  void onClose() {
    super.onClose();
    LocationManager().clearTask();
  }

  void initAccessToken() async {
    if (state.accessToken == null) {
      String tokenUrl =
          "${ApiConfig.baiduApi}grant_type=client_credentials&client_id=${GlobalConfig.ak}&client_secret=${GlobalConfig.sk}";
      dynamic rpJson = await Dio().post(tokenUrl);
      Map<String, dynamic> jsonMap = jsonDecode(rpJson.toString());
      state.accessToken = jsonMap["access_token"];
      print('initAccessToken is:${state.accessToken}');
    }
  }

  void baiduOcr(String base64Image) async {
    dynamic ocrResponse = await Dio().post(
        "${ApiConfig.baiduOcrUrl}${state.accessToken}",
        data: {"image": base64Image, "id_card_side": "front"},
        options: Options(
            contentType: ContentType.parse("application/x-www-form-urlencoded")
                .toString()));
    print('baiduOcr is:$ocrResponse}');
    try {
      Map<String, dynamic> jsonMap = json.decode(ocrResponse.toString());

      String name = jsonMap['words_result']['姓名']['words'];
      print('姓名: $name');
      state.customerBean.customerName = name;
      state.nameController.text = name;

      String address = jsonMap['words_result']['住址']['words'];
      print('住址: $address');

      String idCardNumber = jsonMap['words_result']['公民身份号码']['words'];
      print('公民身份号码: $idCardNumber');
      state.customerBean.idNumber = idCardNumber;
      state.idNumController.text = idCardNumber;

      String birthDate = jsonMap['words_result']['出生']['words'];
      print('出生日期: $birthDate');
    } catch (e) {
      print('OCR解析JSON时发生错误: $e');
      LoadingUtils.showToast("OCR识别失败");
    }
    update();
  }

  void onRefresh() {
    isRefresh = true;
    update();
  }

  //表示进入退出就是刷新
  closePage() {
    if (isRefresh) {
      HDNavigator.close(result: {"refresh": 1});
    } else {
      HDNavigator.close();
    }
  }

  @override
  void dispose() {
    LocationGaode().dispose();
  }

  Future<void> submit(int flag) async {
    if (state.bankController.data.isNotEmpty) {
      state.customerBean.bankCardPhoto = [];
      for (var item in state.bankController.data) {
        state.customerBean.bankCardPhoto!.add(item.id ?? 0);
      }
    }
    if (state.houseCerController.data.isNotEmpty) {
      state.customerBean.houseTitleCertificate = [];
      for (var item in state.houseCerController.data) {
        state.customerBean.houseTitleCertificate!.add(item.id ?? 0);
      }
    }
    if (state.gatePhotoController.data.isNotEmpty) {
      state.customerBean.gatePhoto = [];
      for (var item in state.gatePhotoController.data) {
        state.customerBean.gatePhoto!.add(item.id ?? 0);
      }
    }
    if (state.otherController.data.isNotEmpty) {
      state.customerBean.other = [];
      for (var item in state.otherController.data) {
        state.customerBean.other!.add(item.id ?? 0);
      }
    }
    state.customerBean.saveOrSubmit = flag;
    if(flag == 0){
      CacheUtil().setJson("customerBean",state.customerBean);
      LoadingUtils.showToast("暂存成功");
      closePage();

    }else{
      if (check(flag)) {
        ResponseData response = await DioClient()
            .doPost(ApiConfig.customerInfo, data: state.customerBean);
        if (response.isok) {
          if (response.code == "0") {
            LoadingUtils.showToast(response.msg ?? "提交成功");
            if (flag == 1){
              CacheUtil().remove("customerBean");
            }
            closePage();
          } else {
            LoadingUtils.showToast(response.msg ?? "提交失败");
          }
        } else {
          LoadingUtils.showToast(response.msg ?? "提交失败");
        }
      }
    }
  }

  bool check(int flag) {
    if ((state.customerBean.customerName ?? "").isEmpty) {
      LoadingUtils.showToast("请输入姓名");
      return false;
    }
    if ((state.customerBean.phoneNumber ?? "").isEmpty) {
      LoadingUtils.showToast("请输入手机号");
      return false;
    }
    if ((state.customerBean.idNumber ?? "").isEmpty) {
      LoadingUtils.showToast("请输入身份证号");
      return false;
    }
    if ((state.customerBean.bankName ?? "").isEmpty) {
      LoadingUtils.showToast("请输开户名称");
      return false;
    }
    if ((state.customerBean.bankCardNumber ?? "").isEmpty) {
      LoadingUtils.showToast("请输入银行卡号");
      return false;
    }

    if ((state.customerBean.buildingAddress ?? "").isEmpty) {
      LoadingUtils.showToast("请输入建站地址");
      return false;
    }
    if (state.customerBean.period == null) {
      LoadingUtils.showToast("请选择期数");
      return false;
    }
    if ((state.customerBean.bankCardPhoto??[]).isEmpty) {
      LoadingUtils.showToast("请上传银行卡照片");
      return false;
    }
    if ((state.customerBean.houseTitleCertificate??[]).isEmpty) {
      LoadingUtils.showToast("请上传房屋产权照片");
      return false;
    }
    if ((state.customerBean.gatePhoto??[]).isEmpty) {
      LoadingUtils.showToast("请上传正大门照片");
      return false;
    }
    return true;
  }

  Future<void> initImgUrl() async {
    if ((state.customerBean.bankCardPhoto ?? []).isNotEmpty) {
      List<ImagePickerData> bankCardData =
          await DioClient().requestImgUrl("",tempList:state.customerBean.bankCardPhoto);
      state.bankController.addImages(bankCardData);
    }
    if ((state.customerBean.houseTitleCertificate ??  []).isNotEmpty) {
      List<ImagePickerData> houseData = await DioClient()
          .requestImgUrl("",tempList:state.customerBean.houseTitleCertificate);
      state.houseCerController.addImages(houseData);
    }
    if ((state.customerBean.gatePhoto ??  []).isNotEmpty) {
      List<ImagePickerData> gatePhotoData = await DioClient()
          .requestImgUrl("",tempList:state.customerBean.gatePhoto);
      state.gatePhotoController.addImages(gatePhotoData);
    }
    if ((state.customerBean.other ??  []).isNotEmpty) {
      List<ImagePickerData> otherData =
          await DioClient().requestImgUrl("",tempList:state.customerBean.other);
      state.otherController.addImages(otherData);
    }
    if ((state.customerBean.idNumberPositive ?? []).isNotEmpty) {
      List<ImagePickerData> idNumberPositiveData = await DioClient()
          .requestImgUrl("",tempList:state.customerBean.idNumberPositive);
      if (idNumberPositiveData.isNotEmpty) {
        state.idImgAvatar = idNumberPositiveData[0].filePath;
      }
    }
    if ((state.customerBean.idNumberNegative ?? []).isNotEmpty) {
      List<ImagePickerData> idNumberNegativeData = await DioClient()
          .requestImgUrl("",tempList:state.customerBean.idNumberNegative);
      if (idNumberNegativeData.isNotEmpty) {
        state.idImg = idNumberNegativeData[0].filePath;
      }
    }
    update();
  }
}
